<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <el-form
            v-if="currentPage === Page.Login"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item prop="username">
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  placeholder="用户名"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="200">
              <el-form-item prop="captcha">
                <el-input
                  v-model="ruleForm.captcha"
                  clearable
                  placeholder="验证码"
                  :prefix-icon="
                    useRenderIcon('fluent:shield-keyhole-20-filled')
                  "
                >
                  <template v-slot:append>
                    <ReImageVerify
                      ref="refCaptcha"
                      v-model:code="ruleForm.captchaId"
                    />
                  </template>
                </el-input>
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>

            <Motion :delay="300">
              <div class="text-right mt-4">
                没有账号?<span
                  class="cursor-pointer text-blue-500 hover:text-blue-300"
                  @click="currentPage = Page.Register"
                  >立即注册</span
                >
              </div>
            </Motion>
          </el-form>
          <Register
            v-if="currentPage === Page.Register"
            @onBack="onRegisterBack"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Motion from './utils/motion'
import { useRouter } from 'vue-router'
import { message } from '@/utils/message'
import { useNav } from '@/layout/hooks/useNav'
import type { FormInstance, FormRules } from 'element-plus'
import { useLayout } from '@/layout/hooks/useLayout'
import { useUserStoreHook } from '@/store/modules/user'
import { initRouter, getTopMenu } from '@/router/utils'
import { bg, avatar, illustration } from './utils/static'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from 'vue'
import { useDataThemeChange } from '@/layout/hooks/useDataThemeChange'
import { ReImageVerify } from '@/components/ReImageVerify'

import dayIcon from '@/assets/svg/day.svg?component'
import darkIcon from '@/assets/svg/dark.svg?component'
import Lock from '@iconify-icons/ri/lock-fill'
import User from '@iconify-icons/ri/user-3-fill'
import Register from './Register.vue'
enum Page {
  Login,
  Register
}

const currentPage = ref(Page.Login)
const refCaptcha = ref<InstanceType<typeof ReImageVerify>>()

defineOptions({
  name: 'Login'
})
const router = useRouter()
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()

const { initStorage } = useLayout()
initStorage()

const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange()
dataThemeChange(overallStyle.value)
const { title } = useNav()

const ruleForm = reactive({
  username: import.meta.env.MODE === 'development' ? 'admin' : '',
  password: import.meta.env.MODE === 'development' ? '123456' : '',
  captcha: '',
  captchaId: ''
})

/** 登录校验 */
const loginRules = reactive<FormRules>({
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  captcha: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
})

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      useUserStoreHook()
        .loginByUsername(ruleForm)
        .then(() => {
          // 获取后端路由
          return initRouter().then(() => {
            router.push(getTopMenu(true).path).then(() => {
              message('欢迎回来 ' + useUserStoreHook().username, {
                type: 'success'
              })
            })
          })
        })
        .catch(() => {
          // message('登录失败', { type: 'error' })
          // 刷新 验证码
          if (refCaptcha.value) {
            refCaptcha.value.getImgCode()
          }
        })
        .finally(() => (loading.value = false))
    }
  })
}

const onRegisterBack = (form: { username: string; password: string }) => {
  if (form) {
    ruleForm.username = form.username
    ruleForm.password = form.password
  }
  currentPage.value = Page.Login
}

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (['Enter', 'NumpadEnter'].includes(code)) {
    onLogin(ruleFormRef.value)
  }
}

onMounted(() => {
  window.document.addEventListener('keypress', onkeypress)
})

onBeforeUnmount(() => {
  window.document.removeEventListener('keypress', onkeypress)
})
</script>

<style scoped>
@import url('@/style/login.css');
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
